import os
import json
import time
import sys
import uuid
from datetime import datetime
from flask import Flask, render_template, request, jsonify, Blueprint
# from flask_cors import CORS  # 已删除，不再需要
import subprocess
import tempfile
import shutil
import time

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from main import KnowledgeExplanationAgent
from code_challenges import CodeChallengeManager
from rust_qa_agent import RustQAAgent
from rust_visualizer import RustKnowledgeVisualizer

# 创建Flask应用
app = Flask(__name__)

# 创建蓝图
api_bp = Blueprint('api', __name__)

# 初始化智能体
agent = KnowledgeExplanationAgent()

# 初始化Rust问答代理和知识可视化代理
rust_qa_agent = RustQAAgent()
rust_visualizer = RustKnowledgeVisualizer()
challenge_manager = CodeChallengeManager()

@api_bp.route('/')
def index():
    """渲染主页面"""
    return render_template('index.html', now_timestamp=int(time.time()))

@api_bp.route('/api/chat', methods=['POST'])
def chat():
    """处理聊天请求"""
    try:
        data = request.json
        message = data.get('message', '')
        user_id = data.get('user_id', 'web_user')
        
        if not message:
            return jsonify({
                'status': 'error',
                'message': '消息不能为空'
            })
        
        # 使用RustQAAgent处理问题
        result = rust_qa_agent.answer_question(user_id, message)
        
        if result['status'] == 'error':
            return jsonify({
                'status': 'error',
                'message': result['message']
            })
        
        # 确保返回的answer_markdown是格式化后的字符串
        answer_markdown = result['answer']
        
        # 如果answer_markdown看起来像JSON格式，尝试解析并提取content
        if answer_markdown.startswith('{') and 'choices' in answer_markdown:
            try:
                json_response = json.loads(answer_markdown)
                if "choices" in json_response and len(json_response["choices"]) > 0 and "message" in json_response["choices"][0]:
                    answer_markdown = json_response["choices"][0]["message"]["content"]
            except json.JSONDecodeError:
                # 如果JSON解析失败，保持原样
                pass
        
        return jsonify({
            'status': 'success',
            'answer_markdown': answer_markdown,
            'classification': result.get('classification', {
                'label': 'general',
                'confidence': 0.5
            }),
            'sources': result.get('sources', [])
        })
        
    except Exception as e:
        print(f"聊天处理错误: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'处理请求时出错: {str(e)}'
        })

@api_bp.route('/api/status')
def status():
    """返回API状态信息"""
    return jsonify({
        'status': 'running',
        'message': 'Rust知识解释智能体API正在运行',
        'version': '1.0.0'
    })

@api_bp.route('/api/visualization', methods=['POST'])
def visualization():
    """生成可视化图表"""
    try:
        data = request.json
        topic = data.get('topic', '')
        chart_type = data.get('chart_type', '')
        
        if not topic:
            return jsonify({
                'status': 'error',
                'message': '请提供主题'
            })
        
        # 使用RustKnowledgeVisualizer生成可视化图表，传递chart_type参数
        result = rust_visualizer.generate_knowledge_visualization(topic, chart_type)
        
        if result['status'] == 'error':
            return jsonify({
                'status': 'error',
                'message': result['message']
            })
        
        # 确保返回的响应格式正确
        return jsonify({
            'status': 'success',
            'mermaid_code': result.get('mermaid_code', ''),
            'chart_type': result.get('chart_type', chart_type),
            'title': result.get('topic', topic),
            'description': result.get('description', f"{topic}的可视化图表")
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'生成可视化图表时出错: {str(e)}'
        })



@api_bp.route('/api/topics', methods=['GET'])
def get_topics():
    """获取Rust学习主题列表"""
    try:
        topics = rust_visualizer.get_visualization_topics()
        
        return jsonify({
            'status': 'success',
            'topics': topics
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取主题列表时出错: {str(e)}'
        })

@api_bp.route('/api/chart_types', methods=['GET'])
def get_chart_types():
    """获取可视化图表类型列表"""
    try:
        chart_types = rust_visualizer.get_chart_types()
        
        return jsonify({
            'status': 'success',
            'chart_types': chart_types
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取图表类型列表时出错: {str(e)}'
        })

@api_bp.route('/api/challenges', methods=['GET'])
def get_challenges():
    """获取代码闯关挑战列表"""
    try:
        user_id = request.args.get('user_id', 'web_user')
        challenges = challenge_manager.get_available_challenges(user_id)
        
        return jsonify({
            'status': 'success',
            'challenges': challenges
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取挑战列表失败: {str(e)}'
        }), 500

@api_bp.route('/api/challenge/<challenge_id>', methods=['GET'])
def get_challenge(challenge_id):
    """获取特定挑战详情"""
    try:
        challenge = challenge_manager.get_challenge_by_id(challenge_id)
        
        if not challenge:
            return jsonify({
                'status': 'error',
                'message': '挑战不存在'
            }), 404
            
        return jsonify({
            'status': 'success',
            'challenge': challenge
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取挑战详情失败: {str(e)}'
        }), 500

@api_bp.route('/api/challenge/validate', methods=['POST'])
def validate_challenge():
    """验证挑战答案"""
    try:
        data = request.get_json()
        user_id = data.get('user_id', 'web_user')
        challenge_id = data.get('challenge_id')
        user_answers = data.get('answers', [])
        
        if not challenge_id or not user_answers:
            return jsonify({
                'status': 'error',
                'message': '缺少必要参数'
            }), 400
            
        result = challenge_manager.validate_answer(user_id, challenge_id, user_answers)
        result['status'] = 'success'
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'验证答案失败: {str(e)}'
        }), 500

@api_bp.route('/api/user/progress', methods=['GET'])
def get_user_progress():
    """获取用户进度"""
    try:
        user_id = request.args.get('user_id', 'web_user')
        progress = challenge_manager.get_user_progress(user_id)
        
        return jsonify({
            'status': 'success',
            'progress': progress
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'获取用户进度失败: {str(e)}'
        }), 500

# 主页路由
@app.route('/')
def index():
    """渲染主页"""
    return render_template('index.html')

# 挑战页面路由
@app.route('/challenges')
def challenges():
    """渲染挑战页面"""
    return render_template('challenges.html')

# 新版关卡式挑战页面路由
@app.route('/challenges-new')
def challenges_new():
    """渲染新版关卡式挑战页面"""
    return render_template('challenges_new.html')

# 代码编辑器页面路由
@app.route('/code-editor')
def code_editor():
    """渲染代码编辑器页面"""
    return render_template('code_editor.html')

# 登录页面路由
@app.route('/login')
def login():
    """渲染登录页面"""
    return render_template('login.html')

# 注册蓝图
app.register_blueprint(api_bp)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)